package baidu.shortpath;


/**
 * Carta.java
 *
 * a map for searching
 * called Carta to avoid confusion with Interface map
 * Created: Mon Dec  4 16:45:12 2000
 *
 * @author <a href="mailto: "Phil Green</a>
 * @version
 */


import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class Carta{
  private ArrayList<Maplink> links; // all the links
  private HashSet cities;  // all the cities
  
  //accessors
  public ArrayList<Maplink> getAllLinks() {return links;}
  public HashSet getCities() {return cities;}

  //constructor - empty map
  
  public Carta(){
  links = new ArrayList<Maplink>();
  }
  
  /**
  * add_Link adds a link to a map
  * @param c1 city 1
  * @param c2 city 2
  * @param c cost of the link
  */
  public void add_Link(String c1, String c2, int c){
    Maplink ml=new Maplink(c1,c2,c);
    links.add(ml);
  }
  
  public String toString(){
    StringBuffer buf = new StringBuffer("MAP WITH LINKS\n");
    for (Maplink lnk: links){
    	String lstr = lnk.toString();
    	buf.append(lstr+"\n");
    }
    return buf.toString();
  }
  
  /**
  * get_Links
  * returns all links to/from a given city
  * @param city - the city
  * @return ArrayList of links 
  */
  public ArrayList<Maplink> get_Links(String city){
    ArrayList<Maplink> clinks = new ArrayList<Maplink>();
     for (Maplink l: links){
         if ((city.compareTo(l.get_city1())==0)||(city.compareTo(l.get_city2())==0))
         clinks.add(l);
     }
     
     return clinks;
  }
  
  /**
  * costbetween
  * returns cost between 2 cities
  * @param c1 city 1
  * @param c2 city 2
  */
  
  public int costbetween(String c1,String c2){
    ArrayList<Maplink> c1links=get_Links(c1);
    int ans=-1;
    Iterator i =c1links.iterator();
    while (i.hasNext()&&(ans<0)){
      Maplink l= (Maplink) i.next();
      if (c2.equals(l.get_city1()) || c2.equals(l.get_city2())){
        ans= l.get_cost();
      }
    }
    return ans;
  }
         

  /**
  * mapFromFile
  * reads a map from file
  * @param fname - the file name
  */
    
  public void  mapFromFile(String fname){
    EasyReader rdr = new EasyReader(fname);
    String c1 = rdr.readString();
    while (c1.compareTo("done")!=0){
      links.add(new Maplink(c1, rdr.readString(), rdr.readInt()));
      c1 = rdr.readString();
      }
    findcities(); // uses the links to find the cities
  }
  
  // find all cities on the map
  
  private void findcities(){
    cities= new HashSet();
    for (Maplink l: links){
    	cities.add(l.get_city1());
      cities.add(l.get_city2());
    }
  }
}  
	
      
  

	 
				 
    

  
